const request = require('../../utils/request')

Page({
  data: {
    myIsAdmin: false,
    myUserId: ''
  },
  onLoad(opt) {
    this.data.myIsAdmin = ((opt.myIsAdmin === 'false') ? false : true)
    this.data.myUserId = opt.myUserId

    this.setData({
      myIsAdmin: this.data.myIsAdmin,
      myUserId: this.data.myUserId
    })
    this.getAppletAuthInfo()
  },

  getAppletAuthInfo() {
    request.post('/getAppletAuthInfo', {}).then(res => {
      this.setData({
        wxAllAuth: res.data.wxAllAuth,
        wxDevAuthChecking: res.data.wxDevAuthChecking
      })
    })
  },

  setAppletAuthInfo(obj) {
    request.post('/setAppletAuthInfo', obj).then(res => {
      if (Number(res.code) === 0) {
        this.getAppletAuthInfo()
        return this.successResult('更新成功')
      } else {
        return this.errorResult(res.msg)
      }
    })
  },

  editWxAllAuth(e) {
    let info = {
      userId: this.data.myUserId,
      wxAllAuth: e.currentTarget.dataset.value
    }
    console.log(info);
    this.setAppletAuthInfo(info)
  },

  editWxDevAuthChecking(e) {
    let info = {
      userId: this.data.myUserId,
      wxDevAuthChecking: e.currentTarget.dataset.value
    }
    this.setAppletAuthInfo(info)
  },

  errorResult(errorInfo) {
    wx.showToast({
      title: errorInfo,
      icon: 'error',
      duration: 2000
    })
  },

  successResult(successInfo) {
    wx.showToast({
      title: successInfo,
      icon: 'success',
      duration: 2000
    })
  },

  back() {
    wx.navigateBack({
      delta: 1,
    });
  },

  formSubmit(e) {
    let obj = e.detail.value;
    if (this.formatIsOk(obj)) {
      request.post('/renewDevAuth', obj).then(res => {
        if (Number(res.code) === 0) {
          this.getAppletAuthInfo()
          return this.successResult('更新成功')
        } else {
          return this.errorResult(res.msg)
        }
      })
    }
  },

  formatIsOk(obj) {
    console.log(obj);
    if (!obj.userId) {
      return this.errorResult('用户ID格式错误')
    }
    if (!obj.usageDays) {
      return this.errorResult('时长选择错误')
    }
    return true
  }

})